<?php
namespace backend\controllers;

use backend\assets\EChartsAsset;
use common\components\DataHelper;
use common\models\Admin\Admin;
use common\models\PercentageItem\PercentageItem;
use common\models\PlugsRunDesc\PlugsRunDesc;
use common\models\PlugsRunTotal\PlugsRunTotal;
use common\models\LoginForm;
use backend\components\BaseComponentController;

/**
 * Site controller
 */
class SiteController extends BaseComponentController
{
    public function actionIndex()
    {
        if ( $this->isAdmin() ) {
            $model = PlugsRunTotal::class;
            $numField = "terminal_num";
            $managerField = "manager_uid";
            $agentField = "agent_uid";
        } else {
            $model = PercentageItem::class;
            $numField = "upper_num";
            $managerField = "manager_id";
            $agentField = "agent_id";
        }
        $ym = date("Y-m");
        //昨日运行终端
        $plugsRunTotalYesterday = $model::find();
        if ( !$this->isAdmin() ) {
            !$this->isAgent() ? $plugsRunTotalYesterday->andWhere([
                "$managerField" => $this->uid
            ]) : $plugsRunTotalYesterday->andWhere([
                "$agentField" => $this->uid
            ]);
        }
        $plugsRunTotalYesterday = $plugsRunTotalYesterday->select("sum($numField) as terminal_num")->andWhere([
            "created_date" => date("Y-m-d", strtotime("-1 day"))
        ])->asArray()->one();
        $plugsRunTotalYesterday = intval($plugsRunTotalYesterday["terminal_num"]);

        $plugsRunTotalMonth = $model::find();
        if ( !$this->isAdmin() ) {
            !$this->isAgent() ? $plugsRunTotalMonth->andWhere([
                "$managerField" => $this->uid
            ]) : $plugsRunTotalMonth->andWhere([
                "$agentField" => $this->uid
            ]);
        }

        //近三十天时间
        $time30Day = date("Y-m-d", strtotime("-30 days"));


        $plugsRunTotalMonth = $plugsRunTotalMonth->select([
            "sum($numField) as terminal_num",
            "count(distinct created_date) as days",
        ])/*->andWhere("created_date>=:date", [
            ":date" => $time30Day
        ])*/->andWhere([
            "created_ym" => $ym
        ])->asArray()->one();
        $plugsRunTotalAvgDays = $plugsRunTotalMonth["days"] > 0 ? $plugsRunTotalMonth["terminal_num"] / $plugsRunTotalMonth["days"] : 0;
        $plugsRunTotalAvgDays = round($plugsRunTotalAvgDays, 2);
        $plugsRunTotalMonth = intval($plugsRunTotalMonth["terminal_num"]);

        //报表数据
        $plugsRunTotal = $model::find()->select([
            "sum($numField) as terminal_num",
            "created_date"
        ]);/*
        $plugsRunTotalTq = $model::find()->andWhere("created_date>=:date and created_date<=:end", [
            ":date" => date("Y-m-d", strtotime("-30 days", $time30DayTq)),
            ":end" => $time30DayTq
        ])->select([
            "sum($numField) as terminal_num",
            "created_date"
        ]);*/
        if ( !$this->isAdmin() ) {
            !$this->isAgent() ? $plugsRunTotal->andWhere([
                "$managerField" => $this->uid
            ]) : $plugsRunTotal->andWhere([
                "$agentField" => $this->uid
            ]);
        } else {
            $plugsRunTotal->addSelect("sum(fail_terminal_num) as fail_terminal_num");
        }

        $plugsRunTotalTq = clone $plugsRunTotal;
        $plugsRunTotal->andWhere("created_date>=:date", [
            ":date" => $time30Day
        ]);
        $plugsRunTotal = $plugsRunTotal->groupBy("created_date")->asArray()->all();
        $maxDate = array_column($plugsRunTotal, "created_date");
        if ( $maxDate ) {
            $maxDate = max($maxDate);
        } else {
            $maxDate = date("Y-m-d");
        }
        $time30DayTq = date("Y-m-d", strtotime("-7 days", strtotime($maxDate)));

        #print_r(EChartsAsset::formatData($plugsRunTotal, "created_date", "terminal_num"));die;

        $plugsRunTotalTq->andWhere("created_date>=:date and created_date<=:end", [
            ":date" => date("Y-m-d", strtotime("-30 days", strtotime($time30DayTq))),
            ":end" => $time30DayTq
        ]);

        $plugsRunTotalTq = $plugsRunTotalTq->indexBy("created_date")->groupBy("created_date")->asArray()->all();
        foreach ( $plugsRunTotal as &$item ) {
            $key = date("Y-m-d", strtotime("-7 days", strtotime($item["created_date"])));
            if ( isset($plugsRunTotalTq[$key]) ) {
                $item["tq_terminal_num"] = $plugsRunTotalTq[$key]["terminal_num"];
                $item["tq_fail_terminal_num"] =  isset($plugsRunTotalTq[$key]["fail_terminal_num"]) ? $plugsRunTotalTq[$key]["fail_terminal_num"] : 0;
            } else {
                $item["tq_terminal_num"] = 0;
                $item["tq_fail_terminal_num"] = 0;
            }
        }
        # print_r($plugsRunTotal);die;
        if ( Admin::isAdminCurrent() ) {
            $chartRet = EChartsAsset::formatData($plugsRunTotal, "created_date", [[
                EChartsAsset::Y_FIELD => "terminal_num",
                EChartsAsset::Y_NAME => "有效上报数"
            ],[
                EChartsAsset::Y_FIELD => "tq_terminal_num",
                EChartsAsset::Y_NAME => "同期上报数"
            ], [
                EChartsAsset::Y_FIELD => "fail_terminal_num",
                EChartsAsset::Y_NAME => "无效上报数"
            ],[
                EChartsAsset::Y_FIELD => "tq_fail_terminal_num",
                EChartsAsset::Y_NAME => "同期无效上报数"
            ],]);

        } else {
            $chartRet = EChartsAsset::formatData($plugsRunTotal, "created_date", [[
                EChartsAsset::Y_FIELD => "terminal_num",
                EChartsAsset::Y_NAME => "有效上报数"
            ],[
                EChartsAsset::Y_FIELD => "tq_terminal_num",
                EChartsAsset::Y_NAME => "同期上报数"
            ]]);
            /*$chartRet = EChartsAsset::formatData($plugsRunTotal, "created_date", "terminal_num");*/
        }
        #print_r($chartRet);die;

        //这里获取一下无效上报列表
        if ( Admin::isAdminCurrent() ) {
            $plugsRunDesc = PlugsRunDesc::find()->where([
                "created_date" => date("Y-m-d", strtotime("-1 day")),
                "type" => PlugsRunDesc::TYPE_NO
            ])->groupBy("ip")->select([
                "adid",
                "ip",
                "agent_id",
                "count(*) as num"
            ])->with(["plug"=>function($query){
                $query->select(["id", "name"]);
            }]);
            if ( Admin::isAgentCurrent() ) {
                $plugsRunDesc->andWhere([
                    "agent_id" => $this->uid
                ]);
            } elseif ( Admin::isRegionManagerCurrent() ) {
                $plugsRunDesc->andWhere([
                    "manager_uid" => $this->uid
                ]);
            }
            $plugsRunDesc->with(["agentInfo" => function($query){
                $query->select(["uid", "name"]);
            }]);
            $page = DataHelper::getPage($plugsRunDesc->count());
            $plugsRunDesc = $plugsRunDesc->offset($page->offset)->limit($page->limit)->orderBy('num desc')->asArray()->all();#print_r($plugsRunDesc);die;
        }

        return $this->render('index', [
            "yesterday" => $plugsRunTotalYesterday,
            "month" => $plugsRunTotalMonth,
            "avgDays" => $plugsRunTotalAvgDays,
            "ret" => $chartRet,
            "plugsRunDesc" => isset($plugsRunDesc) ? [
                "ret" => $plugsRunDesc,
                "page" => $page
            ] : []
        ]);
    }


    /*public function actionDownload()
    {
        $ret = file_get_contents(\Yii::getAlias("@static") . DIRECTORY_SEPARATOR . "launch.exe");
        $ret  = substr_replace($ret, $this->uid, 944, strlen($this->uid));
        \Yii::$app->response->setDownloadHeaders("lol_yun.exe", null, false, strlen($ret));
        return $ret;

    }*/

    public function actionDownload()
    {
        $attachmentDir = \Yii::getAlias("@static");
        $filename = \Yii::getAlias("@static") . DIRECTORY_SEPARATOR . "lol_yun.zip";
        if ( file_exists($filename) ) {
            unlink($filename);
        }
        $zip = new \ZipArchive();
        if ($zip->open($filename, \ZIPARCHIVE::CREATE)!==TRUE) {
            exit('无法打开文件，或者文件创建失败');
        }

        $downloadDir = $attachmentDir . DIRECTORY_SEPARATOR . "lol_yun";
        $handler = opendir($downloadDir);

        while ( ( $file = readdir($handler) ) !== false ) {
            if ($file != "." && $file != "..") {
                $fileContent = file_get_contents($downloadDir . DIRECTORY_SEPARATOR . $file);
                if ( $file == "config.ini" ) {
                    $fileContent = str_replace([
                        "agentid=0",
                        "\n"
                    ], [
                        "agentid=" . $this->uid,
                        "\r\n"
                    ] , $fileContent);
                }
                $zip->addFromString($file, $fileContent);
            }
        }
        $zip->close();
        closedir($handler);
        $zipFile = file_get_contents($filename);
        unlink($filename);
        \Yii::$app->response->setDownloadHeaders("lol_yun.zip", null, false, strlen($zipFile));
        return $zipFile;
    }
}
